/**
 * Created by guo.xiaomin on 2017-10-27.
 */
var mtOrder = mongoose.model('mtOrder');
var mtOrderBalance = mongoose.model('mtOrderBalance');
var mtOrderHistory = mongoose.model('mtOrderHistory');

var ExcelJS = require('exceljs');
var Workbook = ExcelJS.Workbook;
var fs = require('fs');
var toolUtil = require('../common/utils/toolUtil');
var async = require('async');
var User = mongoose.model('user');
var RoleApply = mongoose.model('user_role_apply');
var mtOrderCheckLog = mongoose.model('mtOrderCheckLog');
var nodexj = require("xls-to-json");
var Users = mongoose.model('user');
var moment = require('moment');
var nodeXlsx = require('node-xlsx');
var userService = require('./userService');

/*  宝宝树66小区sprint4    add   66后台结算佣金管理.导出订单 luolh  20171027  start   */
exports.exportOrderCommissionService = function (startTime, endTime, userInfo, callback) {

    logger.debug("exportOrderCommissionService real start...");
    try{
        //var limitCount = 100; // mongodb每次查询件数
        var parallelLimitCount = 4; // 限制N个并行
        var exeCount = 0;
        var eachSeriesInnerCount = 0;
        var wb = new Workbook();
        var ws = wb.addWorksheet('commission_order');

        var dataArray = [];
        async.waterfall([
            function(callbackInner) {
               // 导出之前数据处理
                // 1.时间问题
                if (startTime > endTime) {
                    callbackInner({message:"开始时间大于结束时间"});
                } else {
                    // 查询此人是否做过小区大使
                    var startUserTemp = new Date(moment(startTime, "YYYY-MM-DD HH:mm:ss"));
                    var endUserTemp = new Date(moment(endTime, "YYYY-MM-DD HH:mm:ss"));
                    exports.getRoleApplyUsers(startUserTemp, endUserTemp, userInfo, function(err, users){
                        if (err) {
                            logger.error(err);
                            callbackInner(err, null);
                        } else if (users == null || users.length == 0) {
                            logger.error("没有此用户");
                            callbackInner({message:"没有此用户"}, null);
                        } else {
                            callbackInner(null, users);
                        }
                    });
                }
            },
            function(userArray, callbackInner) {
                if (userArray== null || userArray.length == 0) {
                    logger.error("大使数量：0");
                    callbackInner({message:"没有可以导出的数据"});
                } else {
                    // 取得导出订单数量
                    var orParams = [];
                    logger.debug("大使数量:" + userArray.length);
                    for (var i = 0, len = userArray.length; i < len; i++) {
                        orParams.push({shareCommissionUser : userArray[i]._id});
                        orParams.push({selfPurchaseUser : userArray[i]._id});
                        orParams.push({communityCommissionUser : userArray[i]._id});
                        orParams.push({inviterCommissionUser : userArray[i]._id});
                    }
                    var option = {
                        order_time: {"$gte": startTime, "$lte": endTime},
                        "$or":orParams
                    };

                    mtOrder.count(option, function (err, tempUserCount) {
                        logger.info('小区大使订单件数:' + tempUserCount);
                        if(tempUserCount > 0) {
                            // logger.info('分页，每次取得件数:' + limitCount);
                            mtOrder.find(option)
                                .populate('shareCommissionUser', '_id nickName mobilePhone')
                                .populate('selfPurchaseUser', '_id nickName mobilePhone')
                                .populate('communityCommissionUser', '_id nickName mobilePhone')
                                .populate('inviterCommissionUser', '_id nickName mobilePhone')
                                // .skip(0)
                                // .limit(limitCount)
                                .sort({"shareCommissionUser": 1,"selfPurchaseUser": 1,"communityCommissionUser": 1,"inviterCommissionUser": 1, "order_time":1})
                                .exec(function (err2, usersData) {
                                    logger.debug('Users.find...' + usersData.length);
                                    callbackInner(null, usersData);
                                });
                        } else {
                            callbackInner(null, null);
                        }
                    });
                }
            }
        ], function(err, usersData) {
            callback(err, usersData);
        });
    } catch(e) {
        console.log(e);
        callback({message:"系统异常"});
    }
};
/*  宝宝树66小区sprint4    add   66后台结算佣金管理.导出订单 luolh  20171027  end   */

/*  宝宝树66小区sprint4    add   大使佣金订单详情一览.取得数据 luolh  20171031  start   */
exports.getCommissionOrderlListService = function (userId, startTime,endTime,size,index, callback) {
    var data = [];
    var orParams = [];
    orParams.push({shareCommissionUser : userId});
    orParams.push({selfPurchaseUser : userId});
    orParams.push({communityCommissionUser : userId});
    orParams.push({inviterCommissionUser : userId});

    var option = {
        order_time: {"$gte": startTime, "$lte": endTime},
        "$or":orParams
    };
    var sortType = {order_time: -1};

    async.series([
        function (callbackInner) {
            User.findOne({_id: userId}, function (err, result) {
                if (result == null || result.length == 0) {
                    logger.error("没有此用户");
                    callbackInner({message:"没有此用户"});
                } else {
                    callbackInner(null, result);
                }
            });
        },
        function (callbackInner) {
            // total
            mtOrder.count(option, function (err, count) {
                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {
            //pageData
            if (size == -1) {
                // 数据导出全部
                mtOrder.find(option)
                    // .skip(index).limit(size)
                    .populate('shareCommissionUser', '_id nickName mobilePhone')
                    .populate('selfPurchaseUser', '_id nickName mobilePhone')
                    .populate('communityCommissionUser', '_id nickName mobilePhone')
                    .populate('inviterCommissionUser', '_id nickName mobilePhone')
                    .sort(sortType)
                    .exec(function (err, result) {
                    callbackInner(err, result)
                });
            } else {
                // 页面一览
                mtOrder.find(option)
                    .skip(index).limit(size)
                    .populate('shareCommissionUser', '_id nickName mobilePhone')
                    .populate('selfPurchaseUser', '_id nickName mobilePhone')
                    .populate('communityCommissionUser', '_id nickName mobilePhone')
                    .populate('inviterCommissionUser', '_id nickName mobilePhone')
                    .sort(sortType).exec(function (err, result) {
                    callbackInner(err, result)
                });
            }
        },
    ], callback);
};
/*  宝宝树66小区sprint4    add   大使佣金订单详情一览.取得数据 luolh  20171031  end   */


/**宝宝树四期   获取复核日志数据   add pzs 20171031  start**/
exports.getReexamineLogSearch = function (req, callback){
    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (page - 1) * size;

    var opt={};
    if(body.startdate && body.enddate){
        opt['order_time'] = {$gte: decodeURI(body.startdate + ' 00:00:00'), $lt: decodeURI(body.enddate + ' 23:59:59')};
    }
    if(body.errorStatus){
        opt['isError'] = (body.errorStatus == 1);
    }
    async.series({
        list: function (done) {
            mtOrderCheckLog.find(opt).sort('-dateCreated').skip(index).limit(size).exec(function(error, result){
                done(null, result)
            });
        },
        count: function (done) {
            mtOrderCheckLog.count(opt, function(error, result){
                done(null, result);
            });
        }
    }, function (error, result) {
        callback(error, result);
    })
};
/**宝宝树四期   获取复核日志数据   add pzs 20171031  end**/
//结算搜索数据
exports.commissionSettlement = function (req,callback){
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    //var endCount = parseInt((tempUserCount - 1) / limitCount) + 1;
    //获取查询时间数据
    var startDateSelect = req.body.startdate;
    var endDateSelect = req.body.enddate;
    var startUserTemp = new Date(moment(startDateSelect+" 00:00:00", "YYYY-MM-DD HH:mm:ss"));
    var endUserTemp = new Date(moment(endDateSelect+" 23:59:59", "YYYY-MM-DD HH:mm:ss"));
    var nickName = req.body.nickName;
    var resultList=[];

    var totalInfo={
        balanceStatusVal:"",
        shareCommissionSum:0,
        selfPurchaseSum:0,
        communityCommissionSum:0,
        inviterCommissionSum:0,
        newGroupOrderStatusVal0:0,
        newGroupOrderStatusVal1:0,
        totalCommissionSum:0,
        ordernumber:0,
        // 退款订单数
        refundStatusCount:0,
        // 分享订单数据
        share_userOrderCount:0,
        // 自购订单数
        order_userOrderCount:0,
        //小区订单数
        communityOrderCount:0,
        // 被邀请订单数
        inviterOrderCount:0
    }

    async.waterfall([
        function(callbackInner){
            // check
            var dateArr = toolUtil.getArrayDateByStartEndDateMin(startDateSelect, endDateSelect);
            if(!dateArr){
                callbackInner({message:"开始时间和结算时间异常"},null)
            }else{
                callbackInner(null, dateArr);
            }
        },
        function(dateArr, callbackInner){
            var exeDateStartTime = new Date();
            var params = {
                dateArr : dateArr,
                users:[]
            }
            exports.getRoleApplyUsers(startUserTemp, endUserTemp, nickName, function(err, userRoleRess){
                if (err) {
                    params.users = [];
                    logger.error(err);
                    callbackInner(err, params);
                } else if (userRoleRess == null || userRoleRess.length == 0) {
                    params.users = [];
                    logger.error("没有此用户");
                    callbackInner({message:"没有此用户"}, params);
                } else {
                    params.users = userRoleRess;
                    callbackInner(err, params);
                }
            });
        },
        function(params, callbackInner){
            var tempUserCount = params.users.length;
            if(tempUserCount > 0) {
                async.eachSeries(params.users,
                    function(tempUser,callbackeach){
                    var filter = {
                        '$or':[
                            {'shareCommissionUser':tempUser._id},
                            {'selfPurchaseUser':tempUser._id},
                            {'communityCommissionUser':tempUser._id},
                            {'inviterCommissionUser':tempUser._id}
                        ],
                        'order_time' : {$gte: startUserTemp, $lte: endUserTemp},
                        // 'balanceStatus': 2,
                    };
                    // 按照年月日聚合后，取得年月日列表件数即可
                    mtOrder.find(filter)
                        .populate('shareCommissionUser', '_id nickName mobilePhone')
                        .populate('selfPurchaseUser', '_id nickName mobilePhone')
                        .populate('communityCommissionUser', '_id nickName mobilePhone')
                        .populate('inviterCommissionUser', '_id nickName mobilePhone')
                        .sort({order_time : 1, order_id:1})
                        .exec(function (err, appStartDateList) {
                            if(appStartDateList&&appStartDateList.length > 0){
                                var mtOrderObject={};
                                var shareCommissionSum=0;
                                var selfPurchaseSum=0;
                                var communityCommissionSum=0;
                                var inviterCommissionSum=0;
                                // 已成团订单数
                                var newGroupOrderStatusVal0 = 0;
                                // 未成团数
                                var newGroupOrderStatusVal1 = 0;
                                var refundStatusCount=0;
                                var share_userOrderCount=0;
                                var order_userOrderCount=0;
                                var inviterOrderCount=0;
                                var communityOrderCount=0;

                                // 精算类型
                                var balanceStatusVal = "";
                                var lastDay = "";
                                // 订单数订单id
                                var orderIdTmp = "";
                                // 成团单数订单id
                                var newGroupOrderStatusVal0Tmp = "";
                                // 待成团单数订单id
                                var newGroupOrderStatusVal1Tmp = "";
                                // 退款单数订单id
                                var refundStatusCountTmp = "";
                                for(var i = 0 ; i<appStartDateList.length ; i++) {
                                    var tempDay = moment(appStartDateList[i].order_time).format('YYYY-MM-DD');
                                    if (tempDay != lastDay) {
                                        // 把上一个添加到栈中
                                        if (lastDay != "") {
                                            //
                                            totalInfo.shareCommissionSum += new Number(mtOrderObject.shareCommissionSum);
                                            totalInfo.selfPurchaseSum += new Number(mtOrderObject.selfPurchaseSum);
                                            totalInfo.communityCommissionSum += new Number(mtOrderObject.communityCommissionSum);
                                            totalInfo.inviterCommissionSum += new Number(mtOrderObject.inviterCommissionSum);
                                            totalInfo.newGroupOrderStatusVal0 += new Number(mtOrderObject.newGroupOrderStatusVal0);
                                            totalInfo.newGroupOrderStatusVal1 += new Number(mtOrderObject.newGroupOrderStatusVal1);
                                            totalInfo.totalCommissionSum += new Number(mtOrderObject.totalCommissionSum);
                                            totalInfo.ordernumber += new Number(mtOrderObject.ordernumber);
                                            // 退款订单数
                                            totalInfo.refundStatusCount += new Number(mtOrderObject.refundStatusCount);
                                            // 分享订单数据
                                            totalInfo.share_userOrderCount += new Number(mtOrderObject.share_userOrderCount);
                                            // 自购订单数
                                            totalInfo.order_userOrderCount += new Number(mtOrderObject.order_userOrderCount);
                                            //小区订单数
                                            totalInfo.communityOrderCount += new Number(mtOrderObject.communityOrderCount);
                                            // 被邀请订单数
                                            totalInfo.inviterOrderCount += new Number(mtOrderObject.inviterOrderCount);
                                            resultList.push(mtOrderObject);
                                        }
                                        // 新的日期,
                                        lastDay = tempDay;
                                        mtOrderObject = {};
                                        mtOrderObject.order_time = tempDay;
                                        mtOrderObject.uid = tempUser._id.toString();
                                        shareCommissionSum = 0;
                                        selfPurchaseSum = 0;
                                        communityCommissionSum = 0;
                                        inviterCommissionSum = 0;
                                        // 已成团订单数
                                        newGroupOrderStatusVal0 = 0;
                                        // 未成团数
                                        newGroupOrderStatusVal1 = 0;
                                        refundStatusCount = 0;
                                        share_userOrderCount = 0;
                                        order_userOrderCount = 0;
                                        inviterOrderCount = 0;
                                        communityOrderCount = 0;

                                        // 精算类型
                                        balanceStatusVal = "";
                                    }

                                    if (appStartDateList[i].shareCommissionUser != null
                                        && appStartDateList[i].shareCommissionUser._doc != null
                                        && appStartDateList[i].shareCommissionUser._doc._id.toString() == tempUser._id.toString()) {
                                        if (mtOrderObject.nickName == null) {
                                            mtOrderObject.nickName = appStartDateList[i].shareCommissionUser._doc.nickName;
                                            mtOrderObject.mobilePhone = appStartDateList[i].shareCommissionUser._doc.mobilePhone;
                                        }
                                        if (orderIdTmp != appStartDateList[i].order_id.toString()) {
                                            share_userOrderCount++;
                                            orderIdTmp = appStartDateList[i].order_id.toString();
                                        }
                                    } else if (appStartDateList[i].selfPurchaseUser != null
                                        && appStartDateList[i].selfPurchaseUser._doc != null
                                        && appStartDateList[i].selfPurchaseUser._doc._id.toString() == tempUser._id.toString()) {
                                        if (mtOrderObject.nickName == null) {
                                            mtOrderObject.nickName = appStartDateList[i].selfPurchaseUser._doc.nickName;
                                            mtOrderObject.mobilePhone = appStartDateList[i].selfPurchaseUser._doc.mobilePhone;
                                        }
                                        if (orderIdTmp != appStartDateList[i].order_id.toString()) {
                                            order_userOrderCount++;
                                            orderIdTmp = appStartDateList[i].order_id.toString();
                                        }

                                    } else if (appStartDateList[i].communityCommissionUser != null
                                        && appStartDateList[i].communityCommissionUser._doc != null
                                        && appStartDateList[i].communityCommissionUser._doc._id.toString() == tempUser._id.toString()) {
                                        if (mtOrderObject.nickName == null) {
                                            mtOrderObject.nickName = appStartDateList[i].communityCommissionUser._doc.nickName;
                                            mtOrderObject.mobilePhone = appStartDateList[i].communityCommissionUser._doc.mobilePhone;
                                        }
                                        if (orderIdTmp != appStartDateList[i].order_id.toString()) {
                                            communityOrderCount++;
                                            orderIdTmp = appStartDateList[i].order_id.toString();
                                        }
                                    } else if (appStartDateList[i].inviterCommissionUser != null
                                        && appStartDateList[i].inviterCommissionUser._doc != null
                                        && appStartDateList[i].inviterCommissionUser._doc._id.toString() == tempUser._id.toString()) {
                                        if (mtOrderObject.nickName == null) {
                                            mtOrderObject.nickName = appStartDateList[i].inviterCommissionUser._doc.nickName;
                                            mtOrderObject.mobilePhone = appStartDateList[i].inviterCommissionUser._doc.mobilePhone;
                                        }
                                        if (orderIdTmp != appStartDateList[i].order_id.toString()) {
                                            inviterOrderCount++;
                                            orderIdTmp = appStartDateList[i].order_id.toString();
                                        }

                                    } else {
                                        mtOrderObject.nickName = null;
                                        mtOrderObject.mobilePhone = null;
                                    }

                                    if(appStartDateList[i]&&appStartDateList[i].balanceStatus) {
                                        var balanceStatusValTmp = toolUtil.getCommissionStatus(appStartDateList[i],  tempUser._id.toString());
                                        if (balanceStatusValTmp != "") {
                                            // 未处理
                                            if (balanceStatusVal.indexOf(balanceStatusValTmp) < 0) {
                                                balanceStatusVal += (balanceStatusVal.length == 0 ? "" : ",") + balanceStatusValTmp;
                                            }
                                            if (totalInfo.balanceStatusVal.indexOf(balanceStatusValTmp) < 0) {
                                                totalInfo.balanceStatusVal += (totalInfo.balanceStatusVal.length == 0 ? "" : ",") + balanceStatusValTmp;
                                            }
                                        }
                                    }
                                    if ((appStartDateList[i]._doc.shareCommissionUser
                                        &&appStartDateList[i]._doc.shareCommissionUser._id.toString() == tempUser._id.toString())
                                        || (appStartDateList[i]._doc.selfPurchaseUser
                                        && appStartDateList[i]._doc.selfPurchaseUser._id.toString()  == tempUser._id.toString())
                                        || (appStartDateList[i]._doc.communityCommissionUser
                                        && appStartDateList[i]._doc.communityCommissionUser._id.toString()  == tempUser._id.toString())) {
                                        shareCommissionSum+=new Number(appStartDateList[i].shareCommission);
                                        selfPurchaseSum+=new Number(appStartDateList[i].selfPurchase);
                                        communityCommissionSum+=new Number(appStartDateList[i].communityCommission);
                                    } else {
                                        inviterCommissionSum+=new Number(appStartDateList[i].inviterCommission);
                                    }
                                    //已成团订单数
                                    //newGroupOrderStatus : String, // 新版本拼团状态 0-已成团;1-未成团;2-待成团;3-已抢光
                                    if(appStartDateList[i].newGroupOrderStatus==0){
                                        if (newGroupOrderStatusVal0Tmp != appStartDateList[i].order_id.toString()) {
                                            newGroupOrderStatusVal0++
                                            newGroupOrderStatusVal0Tmp = appStartDateList[i].order_id.toString();
                                        }
                                    }
                                    // 未成团单数
                                    if(appStartDateList[i].newGroupOrderStatus==1){
                                        if (newGroupOrderStatusVal1Tmp != appStartDateList[i].order_id.toString()) {
                                            newGroupOrderStatusVal1++
                                            newGroupOrderStatusVal1Tmp = appStartDateList[i].order_id.toString();
                                        }

                                    }
                                    // 退款订单
                                    if(appStartDateList[i].status==100){
                                        if (refundStatusCountTmp != appStartDateList[i].order_id.toString()) {
                                            refundStatusCount++;
                                            refundStatusCountTmp = appStartDateList[i].order_id.toString();
                                        }

                                    }

                                    mtOrderObject.shareCommissionSum=shareCommissionSum;
                                    mtOrderObject.selfPurchaseSum=selfPurchaseSum;
                                    mtOrderObject.communityCommissionSum=communityCommissionSum;
                                    mtOrderObject.inviterCommissionSum=inviterCommissionSum;
                                    mtOrderObject.balanceStatusVal = balanceStatusVal;
                                    mtOrderObject.newGroupOrderStatusVal0 = newGroupOrderStatusVal0;
                                    mtOrderObject.newGroupOrderStatusVal1 = newGroupOrderStatusVal1;
                                    // if ((appStartDateList[i]._doc.shareCommissionUser
                                    //     &&appStartDateList[i]._doc.shareCommissionUser._id.toString() == tempUser._id.toString())
                                    //     || (appStartDateList[i]._doc.selfPurchaseUser
                                    //     && appStartDateList[i]._doc.selfPurchaseUser._id.toString()  == tempUser._id.toString())
                                    //     || (appStartDateList[i]._doc.communityCommissionUser
                                    //     && appStartDateList[i]._doc.communityCommissionUser._id.toString()  == tempUser._id.toString())) {
                                        mtOrderObject.totalCommissionSum = new Number(mtOrderObject.shareCommissionSum
                                            +mtOrderObject.selfPurchaseSum
                                            +mtOrderObject.communityCommissionSum
                                            +mtOrderObject.inviterCommissionSum);
                                    // } else {
                                    //     mtOrderObject.totalCommissionSum = mtOrderObject.inviterCommissionSum;
                                    // }

                                    mtOrderObject.ordernumber = share_userOrderCount + order_userOrderCount + communityOrderCount+inviterOrderCount;
                                    // 退款订单数
                                    mtOrderObject.refundStatusCount = refundStatusCount;
                                    // 分享订单数据
                                    mtOrderObject.share_userOrderCount =share_userOrderCount;
                                    // 自购订单数
                                    mtOrderObject.order_userOrderCount = order_userOrderCount;
                                    //小区订单数
                                    mtOrderObject.communityOrderCount= communityOrderCount;
                                    // 被邀请订单数
                                    mtOrderObject.inviterOrderCount= inviterOrderCount;

                                    if (i == appStartDateList.length - 1) {
                                        //
                                        totalInfo.shareCommissionSum+=new Number(mtOrderObject.shareCommissionSum);
                                        totalInfo.selfPurchaseSum+=new Number(mtOrderObject.selfPurchaseSum);
                                        totalInfo.communityCommissionSum+=new Number(mtOrderObject.communityCommissionSum);
                                        totalInfo.inviterCommissionSum+=new Number(mtOrderObject.inviterCommissionSum);
                                        totalInfo.newGroupOrderStatusVal0 += mtOrderObject.newGroupOrderStatusVal0;
                                        totalInfo.newGroupOrderStatusVal1 += mtOrderObject.newGroupOrderStatusVal1;
                                        totalInfo.totalCommissionSum += new Number(mtOrderObject.totalCommissionSum);
                                        totalInfo.ordernumber += mtOrderObject.ordernumber;
                                        // 退款订单数
                                        totalInfo.refundStatusCount += mtOrderObject.refundStatusCount;
                                        // 分享订单数据
                                        totalInfo.share_userOrderCount += mtOrderObject.share_userOrderCount;
                                        // 自购订单数
                                        totalInfo.order_userOrderCount += mtOrderObject.order_userOrderCount;
                                        //小区订单数
                                        totalInfo.communityOrderCount =+ mtOrderObject.communityOrderCount;
                                        // 被邀请订单数
                                        totalInfo.inviterOrderCount+= mtOrderObject.inviterOrderCount;
                                        // 最后一个
                                        resultList.push(mtOrderObject);
                                    }
                                }
                                callbackeach();
                            } else {
                                callbackeach();
                            }
                        });
                    },
                    function (err) {
                            callbackInner(err, resultList);
                });
            } else {
                callbackInner();
            }
        }
        ],
        function(err){
            var count = resultList.length;
            totalPage = Math.ceil(count/size);
            var resultRelList=[];
            resultList.forEach(function(temp, ind){
                if (ind >= index && ind <= index + size) {
                    resultRelList.push(temp);
                }
            });
            var results = {
                count : resultList.length,
                totalPage : totalPage,
                list : resultRelList,
                totalInfo : totalInfo
            };
            callback(err, results);
    });
};

// 导入数据
exports.commissionImportData = function(req ,callback) {
    var excelData = null;
    var orderid=null;
    if (req.files.excel != null) {
        var filePath = req.files.excel.path;
        logger.debug("filePath:"+filePath);

        var obj = nodeXlsx.parse(filePath);
        // var jsonData = JSON.stringify(obj);
        // console.log(jsonData);
        var data = obj[0].data;
        var count = 0;
        var flg = false;
        if(data.length > 1) {
            exports.getNextBalanceVersion(function (versionErr, versionResult) {
                async.eachSeries(data, function (row, callbackInner) {
                    if (count++ >= 1) {
                        var orderId = row[0];
                        mtOrder.findOne({'order_id': orderId}, {'balanceStatus': 1}, function (findOneErr, findOneResult) {
                            if (findOneErr) {
                                logger.error("mongodb连接异常...");
                                flg = true;
                                callbackInner(true);
                            } else {
                                if (findOneResult) {
                                    var balanceStatus = findOneResult.balanceStatus; // 数据库中结算状态
                                    if (balanceStatus == 0 || balanceStatus == 1) {
                                        logger.debug("balanceStatus..." + balanceStatus);
                                        flg = true;
                                        callbackInner(true);
                                    } else {
                                        callbackInner(false);
                                    }
                                } else {
                                    logger.debug("当前订单对应数据不存在..." + orderId);
                                    flg = true;
                                    callbackInner(true);
                                }
                            }
                        });
                    } else {
                        var orderName = row[0];
                        if (orderName != '订单id') {
                            logger.debug(orderName);
                            flg = true;
                            callbackInner(true);
                        } else {
                            callbackInner(false);
                        }
                    }
                }, function (err) {
                    logger.debug("async.eachSeries01 end...");
                    if (!flg) {
                        count = 0;
                        async.eachSeries(data, function (row, callbackInner) {
                            if (count++ >= 1) {
                                var tempOrderId = row[0]; // 订单ID
                                var orderMoney = row[11]; // 订单佣金
                                // var mobilePhone = row[5]; // 用户手机号
                                if (tempOrderId) {
                                    // 2:已精算，3:本单结算，4:提成结算，5::全部结算
                                    // 2可以变成3,4,5
                                    // 3可以变成5
                                    // 4可以变成5
                                    // 只处理2,3,4
                                    mtOrder.findOne({'order_id': tempOrderId}, {
                                        'shareCommissionUser': 1,
                                        'selfPurchaseUser': 1,
                                        'communityCommissionUser': 1,
                                        'inviterCommissionUser': 1,
                                        'balanceStatus': 1
                                    }, function (findErr, findResult) {
                                        if (findResult) {
                                            // var excelBalanceStatusName = row.结算状态;
                                            // var excelBalanceStatus = toolUtil.getBalanceStatusByName(excelBalanceStatusName);
                                            // logger.debug("订单状态..." + orderid + ':' + excelBalanceStatus);
                                            var balanceStatus = findResult.balanceStatus; // 数据库中结算状态
                                            logger.debug("订单数据库中状态..." + tempOrderId + ':' + balanceStatus);
                                            if (balanceStatus == 5) {
                                                logger.debug("订单数据库中状态5,无需更新..." + tempOrderId);
                                                callbackInner(false);
                                            } else {
                                                var updateFlag = true;
                                                var updateBalanceStatus = 5;
                                                var uid = row[3];
                                                // 之前是提成结算
                                                if (balanceStatus == 4) {
                                                    updateBalanceStatus = 5;
                                                } else if (balanceStatus == 3) {
                                                    // 之前是本单结算
                                                    updateBalanceStatus = 5;
                                                } else if (balanceStatus == 2) {
                                                    var flag = toolUtil.getCommissionUserFlag(findResult, uid);
                                                    logger.debug("订单数状态为2..." + tempOrderId + ':' + flag);
                                                    if (flag) {
                                                        updateBalanceStatus = flag;
                                                    } else {
                                                        updateFlag = false;
                                                    }
                                                }
                                                if (updateFlag) {
                                                    logger.debug("订单状态更新..." + tempOrderId + ':' + updateBalanceStatus);

                                                    var actuarialCommission = 0; // 精算金额
                                                    var estimateCommission = 0; // 粗算金额
                                                    exports.getWaitCloseActuarial(uid, function (getErr, getDocs) {
                                                        // exports.getUserWaitCloseActuarial(uid, function (getErr, getDocs) {
                                                        if(getDocs) {
                                                            logger.debug(getDocs);
                                                            actuarialCommission = Number(getDocs.wait_close).toFixed(2);
                                                            estimateCommission = Number(getDocs.wait_actuarial).toFixed(2);
                                                            logger.debug(actuarialCommission);
                                                            logger.debug(estimateCommission);
                                                        } else {
                                                            logger.debug("getDocs is empty...");
                                                        }
                                                        mtOrder.update({"order_id": tempOrderId}, {"balanceStatus": updateBalanceStatus}, {multi: true}, function (err, docs) {
                                                            // uid,用户mongoid
                                                            // balanceAmbassadorUser
                                                            mtOrderBalance.findOne({'balanceAmbassadorUser': uid, 'balanceVersion' : versionResult}, function (findErr, findResult) {
                                                                var mtOrderBalanceId = null;
                                                                var actuaryMoney = 0;
                                                                async.series([
                                                                    function(seriesCallbackInner) {
                                                                        // 精算的钱以及当前钱进行加减
                                                                        if(findResult) {
                                                                            mtOrderBalanceId = findResult._id;
                                                                            // update 更新
                                                                            actuarialCommission = findResult.actuarialCommission; // 精算金额
                                                                            estimateCommission = findResult.estimateCommission; // 粗算金额
                                                                            // 本次金额 orderMoney
                                                                            // 结算金额
                                                                            var balanceCommission = findResult.balanceCommission + orderMoney;
                                                                            balanceCommission = balanceCommission.toFixed(2);
                                                                            // 结算余额
                                                                            var remainingSum = actuarialCommission - balanceCommission;
                                                                            remainingSum = remainingSum.toFixed(2);
                                                                            // 结算次数
                                                                            var balanceCount = findResult.balanceCount + 1;
                                                                            mtOrderBalance.update({'balanceAmbassadorUser': uid, 'balanceVersion' : versionResult},
                                                                                {'balanceCommission': balanceCommission, 'remainingSum': remainingSum, 'balanceCount': balanceCount, 'dateLastModified': new Date()}).exec(
                                                                                function (updateErr, updateResult) {
                                                                                    if(updateErr) {
                                                                                        logger.error("mtOrderBalance.update error...");
                                                                                    }
                                                                                    logger.debug("mtOrderBalance update success..." + mtOrderBalanceId);
                                                                                    seriesCallbackInner(null, mtOrderBalanceId);
                                                                            });
                                                                        } else {
                                                                            // insert 新增
                                                                            var temp = new mtOrderBalance();
                                                                            temp.balanceAmbassadorUser = uid; // 大使用户id
                                                                            temp.actuarialCommission = actuarialCommission; // 精算金额
                                                                            temp.estimateCommission = estimateCommission; // 粗算金额
                                                                            temp.balanceCommission = orderMoney; // 结算金额
                                                                            temp.remainingSum = actuarialCommission - orderMoney; // 结算余额
                                                                            temp.balanceVersion = versionResult; // 结算版本
                                                                            temp.balanceCount = 1;
                                                                            temp.balance_time = new Date(); // 结算时间
                                                                            temp.dateLastModified = new Date();
                                                                            temp.save(function (saveErr, saveResult) {
                                                                                mtOrderBalanceId = saveResult._id;
                                                                                logger.debug("mtOrderBalance save success..." + mtOrderBalanceId);
                                                                                seriesCallbackInner(null, mtOrderBalanceId);
                                                                            });
                                                                        }
                                                                    }
                                                                ], function(err, result) {
                                                                    // 拷贝数据到历史表中
                                                                    exports.copyDataToMtOrderHistoryByOrderId(tempOrderId, mtOrderBalanceId, function (copyErr, copyDocs) {
                                                                        logger.debug("copyDataToHistory..." + tempOrderId + "@" + mtOrderBalanceId);
                                                                        callbackInner(false);
                                                                    });
                                                                });
                                                            })
                                                        });
                                                    });
                                                } else {
                                                    callbackInner(false);
                                                }

                                            }
                                        } else {
                                            logger.debug("mtOrder.findOne 返回数据为空...");
                                            flg = true;
                                            callbackInner(true);
                                        }
                                    });
                                } else {
                                    callbackInner(false);
                                }
                            } else {
                                callbackInner(false);
                            }
                        }, function (err) {
                            logger.debug("async.eachSeries02 end...");
                            callback(err, null);
                        })
                    } else {
                        logger.debug("存在不可结算数据...");
                        callback(1, null);
                    }
                });
            });
        } else {
            logger.debug("存在不可结算数据...");
            callback(1, null);
        }
        // try {
        //     nodexj({
        //         input: filePath  // input xls
        //         ,output: null // output json
        //     }, function (err, result) {
        //         logger.error(err);
        //         if (err) {
        //             fs.unlink(filePath);
        //             callback(err, null);
        //         } else {
        //             logger.debug("fs.unlink");
        //             fs.unlink(filePath);
        //             var flg = false;
        //             console.log(result);
        //             excelData = result;
        //             // for(var i = 0 ; i < result.size ; i++){
        //             //     if(result[i]&&result[i].balanceStatus&&result[i].balanceStatus=='已粗算'){
        //             //         //说明有为精算的订单
        //             //         flg=true;
        //             //         break;
        //             //         callback(1, null);
        //             //     }
        //             //     return;
        //             // }
        //
        //             async.eachSeries(excelData, function (row, callbackInner) {
        //                 mtOrder.findOne({'order_id': row.订单id}, {'balanceStatus': 1}, function (findOneErr, findOneResult) {
        //                     if (findOneResult) {
        //                         var balanceStatus = findOneResult.balanceStatus; // 数据库中结算状态
        //                         if (balanceStatus == 0 || balanceStatus == 1) {
        //                             flg = true;
        //                             callbackInner(true);
        //                         } else {
        //                             callbackInner(false);
        //                         }
        //                     }
        //                 });
        //             }, function (err) {
        //                 if (flg == false) {
        //                     if (!(result[0].订单id)) {
        //                         callback(1, null);
        //                     } else {
        //                         async.eachSeries(excelData, function (row, callbackInner) {
        //                             orderid = row.订单id;
        //                             if (orderid) {
        //                                 // 2:已精算，3:本单结算，4:提成结算，5::全部结算
        //                                 // 2可以变成3,4,5
        //                                 // 3可以变成5
        //                                 // 4可以变成5
        //                                 // 只处理2,3,4
        //                                 mtOrder.findOne({'order_id': orderid}, {
        //                                     'shareCommissionUser': 1,
        //                                     'selfPurchaseUser': 1,
        //                                     'communityCommissionUser': 1,
        //                                     'inviterCommissionUser': 1,
        //                                     'balanceStatus': 1
        //                                 }, function (findErr, findResult) {
        //                                     if (findResult) {
        //                                         // var excelBalanceStatusName = row.结算状态;
        //                                         // var excelBalanceStatus = toolUtil.getBalanceStatusByName(excelBalanceStatusName);
        //                                         // logger.debug("订单状态..." + orderid + ':' + excelBalanceStatus);
        //                                         var balanceStatus = findResult.balanceStatus; // 数据库中结算状态
        //                                         logger.debug("订单数据库中状态..." + orderid + ':' + balanceStatus);
        //                                         if (balanceStatus == 5) {
        //                                             logger.debug("订单数据库中状态5,无需更新..." + orderid);
        //                                             callbackInner(false);
        //                                         } else {
        //                                             var updateFlag = true;
        //                                             var updateBalanceStatus = 5;
        //                                             var uid = row.UID;
        //                                             // 之前是提成结算
        //                                             if (balanceStatus == 4) {
        //                                                 updateBalanceStatus = 5;
        //                                             } else if (balanceStatus == 3) {
        //                                                 // 之前是本单结算
        //                                                 updateBalanceStatus = 5;
        //                                             } else if (balanceStatus == 2) {
        //                                                 var flag = toolUtil.getCommissionUserFlag(findResult, uid);
        //                                                 logger.debug("订单数状态为2..." + orderid + ':' + flag);
        //                                                 if (flag) {
        //                                                     updateBalanceStatus = flag;
        //                                                 } else {
        //                                                     updateFlag = false;
        //                                                 }
        //                                             }
        //                                             if (updateFlag) {
        //                                                 logger.debug("订单状态更新..." + orderid + ':' + updateBalanceStatus);
        //                                                 mtOrder.update({"order_id": orderid}, {"balanceStatus": updateBalanceStatus}, {multi: true}, function (err, docs) {
        //                                                     callbackInner(false);
        //                                                 })
        //                                             } else {
        //                                                 callbackInner(false);
        //                                             }
        //
        //                                         }
        //                                     }
        //                                 });
        //                             }
        //                         }, function (err) {
        //                             callback(err, null);
        //                         })
        //                     }
        //                 } else {
        //                     logger.debug("存在不可结算数据...");
        //                     callback(1, null);
        //                 }
        //             });
        //         }
        //
        //     });
        // } catch(e) {
        //     console.log(e);
        //     callback('fail', null);
        // }
    }
    else {
        callback(null, null);
    }
};

// 取得小区大使用户数据
exports.getRoleApplyUsers = function(startUserTemp, endUserTemp, nickName,callbackInner) {
    if (nickName != null && nickName != "") {
        User.find(
            {_id:nickName}
        ).exec(function (err, userRes) {
            if (userRes == null || userRes.length == 0) {
                User.find({$or:[
                    {mobilePhone:nickName},
                    {nickName:nickName}
                ]}).exec(function (err, userResMn) {
                    userRes = userResMn;
                    // 用户条件
                    if (userRes == null || userRes.length == 0) {
                        callbackInner();
                    } else {
                        var orParam = [];
                        userRes.forEach(function(groupUser){
                            orParam.push({user : groupUser._doc._id});
                        });
                        RoleApply.aggregate([
                            {$match:{
                                type:4
                                ,startDateTime:{$lte:endUserTemp}
                                ,endDateTime:{$gte:startUserTemp}
                                ,$or:orParam
                            }},
                            // {$group:{_id:{user:"$user", startDateTime:"$startDateTime",endDateTime:"$endDateTime"}}}
                            {$group:{_id:"$user"}}
                        ]).exec(function(err, userRoleRess){
                            callbackInner(err, userRoleRess);
                        });
                    }
                });
            } else {
                    var orParam = [];
                    userRes.forEach(function(groupUser){
                        orParam.push({user : groupUser._doc._id});
                    });
                    RoleApply.aggregate([
                        {$match:{
                            type:4
                            ,startDateTime:{$lte:endUserTemp}
                            ,endDateTime:{$gte:startUserTemp}
                            ,$or:orParam
                        }},
                        // {$group:{_id:{user:"$user", startDateTime:"$startDateTime",endDateTime:"$endDateTime"}}}
                        {$group:{_id:"$user"}}
                    ]).exec(function(err, userRoleRess){
                        callbackInner(err, userRoleRess);
                    });
                }
        });
    } else {
        // 用户条件
        RoleApply.aggregate([
            {$match:{
                $or:[{type:4,status:-1,startDateTime:{$lte:endUserTemp},endDateTime:{$gte:startUserTemp}}
                ,{type:4,status:1,startDateTime:{$lte:endUserTemp},endDateTime:{$gte:startUserTemp}}]
            }},
            {$group:{_id:"$user"}}
        ]).exec(function(err, userRoleRess){
                callbackInner(err, userRoleRess);
        });
    }
}

//订单佣金数据导出
exports.exportCommissionOrderService= function (req,callback){
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    //var endCount = parseInt((tempUserCount - 1) / limitCount) + 1;
    //获取查询时间数据
    var startDateSelect = req.cparams.startDate;
    var endDateSelect = req.cparams.endDate;
    var startUserTemp = new Date(moment(startDateSelect+" 00:00:00", "YYYY-MM-DD HH:mm:ss"));
    var endUserTemp = new Date(moment(endDateSelect+" 23:59:59", "YYYY-MM-DD HH:mm:ss"));
    var nickName = req.cparams.userInfo;
    if (nickName == true) {
        nickName = null;
    }
    var resultList=[];

    var totalInfo={
        balanceStatusVal:"",
        shareCommissionSum:0,
        selfPurchaseSum:0,
        communityCommissionSum:0,
        inviterCommissionSum:0,
        newGroupOrderStatusVal0:0,
        newGroupOrderStatusVal1:0,
        totalCommissionSum:0,
        ordernumber:0,
        // 退款订单数
        refundStatusCount:0,
        // 分享订单数据
        share_userOrderCount:0,
        // 自购订单数
        order_userOrderCount:0,
        //小区订单数
        communityOrderCount:0,
        // 被邀请订单数
        inviterOrderCount:0
    }

    async.waterfall([
            function(callbackInner){
                // check
                var dateArr = toolUtil.getArrayDateByStartEndDateMin(startDateSelect, endDateSelect);
                if(!dateArr){
                    callbackInner({message:"开始时间和结算时间异常"},null)
                }else{
                    callbackInner(null, dateArr);
                }
            },
            function(dateArr, callbackInner){
                var exeDateStartTime = new Date();
                var params = {
                    dateArr : dateArr,
                    users:[]
                }
                exports.getRoleApplyUsers(startUserTemp, endUserTemp, nickName, function(err, userRoleRess){
                    if (err) {
                        params.users = [];
                        logger.error(err);
                        callbackInner(err, params);
                    } else if (userRoleRess == null || userRoleRess.length == 0) {
                        params.users = [];
                        logger.error("没有此用户");
                        callbackInner({message:"没有此用户"}, params);
                    } else {
                        params.users = userRoleRess;
                        callbackInner(err, params);
                    }
                });
            },
            function(params, callbackInner){
                var tempUserCount = params.users.length;
                if(tempUserCount > 0) {
                    async.eachSeries(params.users,
                        function(tempUser,callbackeach){
                            var filter = {
                                '$or':[
                                    {'shareCommissionUser':tempUser._id},
                                    {'selfPurchaseUser':tempUser._id},
                                    {'communityCommissionUser':tempUser._id},
                                    {'inviterCommissionUser':tempUser._id}
                                ],
                                'order_time' : {$gte: startUserTemp, $lte: endUserTemp},
                                // 'balanceStatus': 2,
                            };
                            // 按照年月日聚合后，取得年月日列表件数即可
                            mtOrder.find(filter)
                                .populate('shareCommissionUser', '_id nickName mobilePhone')
                                .populate('selfPurchaseUser', '_id nickName mobilePhone')
                                .populate('communityCommissionUser', '_id nickName mobilePhone')
                                .populate('inviterCommissionUser', '_id nickName mobilePhone')
                                .sort({order_time : 1,order_id:1})
                                .exec(function (err, appStartDateList) {
                                    if (appStartDateList != null && appStartDateList.length > 0) {
                                        async.each(appStartDateList, function(item, callback) {
                                                if (item._doc.shareCommissionUser != null
                                                    && item._doc.shareCommissionUser._id.toString() == tempUser._id.toString()){
                                                    item._doc.uidVal = item._doc.shareCommissionUser._doc._id.toString();
                                                    item._doc.nickNameVal = item._doc.shareCommissionUser._doc.nickName;
                                                    item._doc.mobilePhoneVal = item._doc.shareCommissionUser._doc.mobilePhone;
                                                } else if (item._doc.selfPurchaseUser != null
                                                    && item._doc.selfPurchaseUser._doc._id.toString() == tempUser._id.toString()){
                                                    item._doc.uidVal = item._doc.selfPurchaseUser._doc._id.toString();
                                                    item._doc.nickNameVal = item._doc.selfPurchaseUser._doc.nickName;
                                                    item._doc.mobilePhoneVal = item._doc.selfPurchaseUser._doc.mobilePhone;
                                                } else if (item._doc.communityCommissionUser != null
                                                    && item._doc.communityCommissionUser._doc._id.toString() == tempUser._id.toString()){
                                                    item._doc.uidVal = item._doc.communityCommissionUser._doc._id.toString();
                                                    item._doc.nickNameVal = item._doc.communityCommissionUser._doc.nickName;
                                                    item._doc.mobilePhoneVal = item._doc.communityCommissionUser._doc.mobilePhone;
                                                } else if (item._doc.inviterCommissionUser != null
                                                    && item._doc.inviterCommissionUser._doc._id.toString() == tempUser._id.toString()){
                                                    item._doc.uidVal = item._doc.inviterCommissionUser._doc._id.toString();
                                                    item._doc.nickNameVal = item._doc.inviterCommissionUser._doc.nickName;
                                                    item._doc.mobilePhoneVal = item._doc.inviterCommissionUser._doc.mobilePhone;
                                                }
                                                callback(null);
                                        }, function(err) {
                                            resultList = resultList.concat(appStartDateList);
                                        });
                                    }
                                    callbackeach();
                                });
                        },
                        function (err) {
                            callbackInner(err, resultList);
                        });
                } else {
                    callbackInner();
                }
            }
        ],
        function(err){
            callback(err, resultList);
        });
};

exports.copyDataToMtOrderHistoryByOrderId = function (orderId, balance_id, callback){
    mtOrder.find({"order_id" : orderId}).sort({"sku_code" : 1}).exec(function (err, orderList) {
        if(orderList) {
            var length = orderList.length;
            logger.debug("当前订单ID共N条数据..." + orderId + "@" + length);
            // 循环
            async.eachSeries(orderList, function (row, callbackEach) {
                var tempSave = exports.copyRowDataToMtOrderHistory(row);
                tempSave.balance_id = balance_id;
                tempSave.save(function (saveErr, result) {
                    if(saveErr) {
                        logger.error("当前订单ID插入到历史表失败..." + orderId);
                    } else {
                        logger.debug("当前订单ID插入到历史表..." + orderId);
                    }
                    callbackEach(false);
                });
            }, function (err) {
                logger.debug("当前订单ID插入到历史表完成..." + orderId + "@" + length);
                callback(null, length);
            })
        } else {
            logger.debug("当前订单ID共0条数据..." + orderId);
            callback(null, 0);
        }
    });
};

exports.copyRowDataToMtOrderHistory = function (row){
    var temp = new mtOrderHistory();
    // 历史数据创建时间
    temp.historyCreated = new Date();
    // 原表唯一ID
    if(toolUtil.isNotUndefined(row._id)) {
        temp.mtOrder_id = row._id;
    }
    if(toolUtil.isNotUndefined(row.order_id)) {
        temp.order_id = row.order_id;
    }
    if(toolUtil.isNotUndefined(row.member_id)) {
        temp.member_id = row.member_id;
    }
    if(toolUtil.isNotUndefined(row.order_uid)) {
        temp.order_uid = row.order_uid;
    }
    if(toolUtil.isNotUndefined(row.order_uhp)) {
        temp.order_uhp = row.order_uhp;
    }
    if(toolUtil.isNotUndefined(row.order_user)) {
        temp.order_user = row.order_user;
    }
    if(toolUtil.isNotUndefined(row.is_order_moderator)) {
        temp.is_order_moderator = row.is_order_moderator;
    }
    if(toolUtil.isNotUndefined(row.share_uid)) {
        temp.share_uid = row.share_uid;
    }
    if(toolUtil.isNotUndefined(row.share_uhp)) {
        temp.share_uhp = row.share_uhp;
    }
    if(toolUtil.isNotUndefined(row.share_user)) {
        temp.share_user = row.share_user;
    }
    if(toolUtil.isNotUndefined(row.is_share_moderator)) {
        temp.is_share_moderator = row.is_share_moderator;
    }
    if(toolUtil.isNotUndefined(row.order_time)) {
        temp.order_time = row.order_time;
    }
    if(toolUtil.isNotUndefined(row.price)) {
        temp.price = row.price;
    }
    if(toolUtil.isNotUndefined(row.total)) {
        temp.total = row.total;
    }
    if(toolUtil.isNotUndefined(row.sku_code)) {
        temp.sku_code = row.sku_code;
    }
    if(toolUtil.isNotUndefined(row.sku_name)) {
        temp.sku_name = row.sku_name;
    }
    if(toolUtil.isNotUndefined(row.quantity)) {
        temp.quantity = row.quantity;
    }
    if(toolUtil.isNotUndefined(row.skuQuantity)) {
        temp.skuQuantity = row.skuQuantity;
    }
    if(toolUtil.isNotUndefined(row.skuSubTotal)) {
        temp.skuSubTotal = row.skuSubTotal;
    }
    if(toolUtil.isNotUndefined(row.itemSaleType)) {
        temp.itemSaleType = row.itemSaleType;
    }
    <!--  宝宝树66小区六次改造 自营非自营 mod   guo.xiaomin  20171222  start   -->
    if(toolUtil.isNotUndefined(row.originalItemSaleType)) {
        temp.originalItemSaleType = row.originalItemSaleType;
    }
    <!--  宝宝树66小区六次改造 自营非自营 mod   guo.xiaomin  20171222  end   -->
    if(toolUtil.isNotUndefined(row.wavesSign)) {
        temp.wavesSign = row.wavesSign;
    }
    if(toolUtil.isNotUndefined(row.standard)) {
        temp.standard = row.standard;
    }
    if(toolUtil.isNotUndefined(row.originalStandard)) {
        temp.originalStandard = row.originalStandard;
    }
    if(toolUtil.isNotUndefined(row.largeId)) {
        temp.largeId = row.largeId;
    }
    if(toolUtil.isNotUndefined(row.mediumId)) {
        temp.mediumId = row.mediumId;
    }
    if(toolUtil.isNotUndefined(row.smallId)) {
        temp.smallId = row.smallId;
    }
    if(toolUtil.isNotUndefined(row.orderType)) {
        temp.orderType = row.orderType;
    }
    if(toolUtil.isNotUndefined(row.isNewGroupOrder)) {
        temp.isNewGroupOrder = row.isNewGroupOrder;
    }
    if(toolUtil.isNotUndefined(row.newGroupOrderStatus)) {
        temp.newGroupOrderStatus = row.newGroupOrderStatus;
    }
    if(toolUtil.isNotUndefined(row.promotionId)) {
        temp.promotionId = row.promotionId;
    }
    if(toolUtil.isNotUndefined(row.proBizCode)) {
        temp.proBizCode = row.proBizCode;
    }
    if(toolUtil.isNotUndefined(row.balanceStatus)) {
        temp.balanceStatus = row.balanceStatus;
    }
    if(toolUtil.isNotUndefined(row.commissionPercent)) {
        temp.commissionPercent = row.commissionPercent;
    }
    if(toolUtil.isNotUndefined(row.commissionName)) {
        temp.commissionName = row.commissionName;
    }
    if(toolUtil.isNotUndefined(row.comment)) {
        temp.comment = row.comment;
    }
    if(toolUtil.isNotUndefined(row.lastActuaryDate)) {
        temp.lastActuaryDate = row.lastActuaryDate;
    }
    if(toolUtil.isNotUndefined(row.shareCommission)) {
        temp.shareCommission = row.shareCommission;
    }
    if(toolUtil.isNotUndefined(row.selfPurchase)) {
        temp.selfPurchase = row.selfPurchase;
    }
    if(toolUtil.isNotUndefined(row.communityCommission)) {
        temp.communityCommission = row.communityCommission;
    }
    if(toolUtil.isNotUndefined(row.inviterCommission)) {
        temp.inviterCommission = row.inviterCommission;
    }
    if(toolUtil.isNotUndefined(row.shareCommissionUser)) {
        temp.shareCommissionUser = row.shareCommissionUser;
    }
    if(toolUtil.isNotUndefined(row.selfPurchaseUser)) {
        temp.selfPurchaseUser = row.selfPurchaseUser;
    }
    if(toolUtil.isNotUndefined(row.communityCommissionUser)) {
        temp.communityCommissionUser = row.communityCommissionUser;
    }
    if(toolUtil.isNotUndefined(row.inviterCommissionUser)) {
        temp.inviterCommissionUser = row.inviterCommissionUser;
    }
    if(toolUtil.isNotUndefined(row.commissionDrawPercentage)) {
        temp.commissionDrawPercentage = row.commissionDrawPercentage;
    }
    if(toolUtil.isNotUndefined(row.orderCommissionType)) {
        temp.orderCommissionType = row.orderCommissionType;
    }
    if(toolUtil.isNotUndefined(row.isInviterCommissionStatus)) {
        temp.isInviterCommissionStatus = row.isInviterCommissionStatus;
    }
    if(toolUtil.isNotUndefined(row.prepareCommissionPrice)) {
        temp.prepareCommissionPrice = row.prepareCommissionPrice;
    }
    if(toolUtil.isNotUndefined(row.realCommissionPrice1)) {
        temp.realCommissionPrice1 = row.realCommissionPrice1;
    }
    if(toolUtil.isNotUndefined(row.realCommissionPrice2)) {
        temp.realCommissionPrice2 = row.realCommissionPrice2;
    }
    if(toolUtil.isNotUndefined(row.status)) {
        temp.status = row.status;
    }
    if(toolUtil.isNotUndefined(row.modifyTime)) {
        temp.modifyTime = row.modifyTime;
    }
    if(toolUtil.isNotUndefined(row.doneTime)) {
        temp.doneTime = row.doneTime;
    }
    if(toolUtil.isNotUndefined(row.refundStatus)) {
        temp.refundStatus = row.refundStatus;
    }
    if(toolUtil.isNotUndefined(row.refundTime)) {
        temp.refundTime = row.refundTime;
    }
    if(toolUtil.isNotUndefined(row.isValid)) {
        temp.isValid = row.isValid;
    }
    if(toolUtil.isNotUndefined(row.dateCreated)) {
        temp.dateCreated = row.dateCreated;
    }
    if(toolUtil.isNotUndefined(row.dateLastModified)) {
        temp.dateLastModified = row.dateLastModified;
    }
    return temp;
};

// 取得下一次结算版本号
exports.getNextBalanceVersion = function (callback){
    mtOrderBalance.findOne({}).sort({"balanceVersion" : -1}).exec(function (err, result) {
        if(result) {
            var temp = result.balanceVersion;
            if(temp) {
                callback(null, temp + 1);
            } else {
                callback(null, 1);
            }
        } else {
            callback(null, 1);
        }
    });
};

// 根据用户id取得待精算和待结算佣金
exports.getWaitCloseActuarial = function (userId, callback)  {

    //获取75天以前的日期
    // var curtDate  = new Date().getTime();
    // var diffDate = 75*24*60*60*1000; // 75天的时间值
    // var borDate = curtDate-diffDate ; // 75天之前的时间戳
    //
    // var timeCurt =( new Date(curtDate));//.Format('yyyy-MM-dd');
    // var timeBor = (new Date(borDate));//.Format('yyyy-MM-dd');

    //待结算与待精算 处理逻辑是一样的，唯一不一样的地方是查询的时间不同
    var filterUserId = mongoose.Types.ObjectId(userId);
    // var filterUserId = userId;
    // 分享,小区,自购
    var fWaitClose = [
        { '$match' : {
            '$or':[
                {'shareCommissionUser':filterUserId },
                {'selfPurchaseUser':filterUserId },
                {'communityCommissionUser': filterUserId }
            ],
            'balanceStatus' : 2 ,  //待结算==已精算
            // 'order_time': {'$lte':timeBor}
        } },
        {'$group' : {
            '_id' : 0, //无关紧要
            'shareCommission' : {'$sum' : '$shareCommission'},
            'selfPurchase': {'$sum': "$selfPurchase"},
            'communityCommission':{'$sum': '$communityCommission'}
        }
        } ];
    // 邀请
    var fWaitCloseInvator = [
        { '$match' : {
            '$or':[
                {'inviterCommissionUser':filterUserId }
            ],
            'balanceStatus' : 2 ,  //待结算==已精算
            // 'order_time': {'$lte':timeBor}
        } },
        {'$group' : {
            '_id' : 0, //无关紧要
            'inviterCommission':{'$sum': '$inviterCommission'}
        }
        } ];

    var fWaitActuarial = [
        { '$match' : {
            '$or':[
                {'shareCommissionUser':filterUserId },
                {'selfPurchaseUser':filterUserId },
                {'communityCommissionUser': filterUserId }
            ],
            'balanceStatus' : 1,  //待精算== 已粗算
            //'order_time': {'$lte':timeCurt, "$gt":timeBor}
        } },
        {'$group' : {
            '_id' : 0, //无关紧要
            'shareCommission' : {'$sum' : '$shareCommission'},
            'selfPurchase': {'$sum': "$selfPurchase"},
            'communityCommission':{'$sum': '$communityCommission'}
        }
        } ];

    var fWaitActuarialInvator = [
        { '$match' : {
            '$or':[
                {'inviterCommissionUser':filterUserId }
            ],
            'balanceStatus' : 1,  //待精算== 已粗算
            //'order_time': {'$lte':timeCurt, "$gt":timeBor}
        } },
        {'$group' : {
            '_id' : 0, //无关紧要
            'inviterCommission':{'$sum': '$inviterCommission'}
        }
        } ];

    async.series({
        wait_close: function (done) {
            mtOrder.aggregate(fWaitClose).exec(function (error, result){
                if(result && result.length >0){
                    var close = 0;
                    if(result != null && result[0]!= null && result[0].shareCommission != null)
                        close += result[0].shareCommission;
                    if(result != null && result[0]!= null && result[0].selfPurchase != null)
                        close += result[0].selfPurchase;
                    if(result != null && result[0]!= null && result[0].communityCommission != null)
                        close += result[0].communityCommission;
                    mtOrder.aggregate(fWaitCloseInvator).exec(function (error, resultInvator){
                        if(resultInvator!=null && resultInvator[0]!= null && resultInvator[0].inviterCommission != null)
                            close += resultInvator[0].inviterCommission;
                        done(null, close)
                    });
                }
                else{
                    var close = 0;
                    mtOrder.aggregate(fWaitCloseInvator).exec(function (error, resultInvator){
                        if(resultInvator!=null && resultInvator[0]!= null && resultInvator[0].inviterCommission != null)
                            close += resultInvator[0].inviterCommission;
                        done(null, close)
                    });
                    // done(null, close);
                }
            });
        },
        wait_actuarial: function (done) {
            mtOrder.aggregate(fWaitActuarial).exec(function (error, result){
                if(result && result.length >0){
                    var actuarial = 0;
                    if(result != null && result[0]!= null && result[0].shareCommission != null)
                        actuarial += result[0].shareCommission;
                    if(result != null && result[0]!= null && userId && result[0].selfPurchase != null)
                        actuarial += result[0].selfPurchase;
                    if(result != null && result[0]!= null && result[0].communityCommission != null)
                        actuarial += result[0].communityCommission;
                    mtOrder.aggregate(fWaitActuarialInvator).exec(function (error, resultInvator){
                        if(resultInvator!=null && resultInvator[0]!= null && resultInvator[0].inviterCommission != null)
                            actuarial += resultInvator[0].inviterCommission;
                        done(null, actuarial)
                    });
                }
                else{
                    var actuarial = 0;
                    mtOrder.aggregate(fWaitActuarialInvator).exec(function (error, resultInvator){
                        if(resultInvator!=null && resultInvator[0]!= null && resultInvator[0].inviterCommission != null)
                            actuarial += resultInvator[0].inviterCommission;
                        done(null, actuarial)
                    });
                    // done(null, actuarial);
                }
            });
        }
    }, function (error, result) {
        callback(error, result);
    })
};

// exports.getUserWaitCloseActuarial = function(userId, balanceStatus, callback)  {
//     // async.parallel({
//     async.series({
//         wait_close: function (done) {
//             exports.getSelfPurchase(userId, 2, done);
//         },
//         wait_actuarial: function (done) {
//             exports.getSelfPurchase(userId, 1, done);
//         }
//     }, function (error, result) {
//         callback(error, result);
//     })
// };
//
// exports.getActuarialEstimateCommissionByUserIdAndBalanceStatus = function(userId, balanceStatus, callback)  {
//     var filterUserId = mongoose.Types.ObjectId(userId);
//     var findOption = {
//         '$or':[
//             {'shareCommissionUser':filterUserId },
//             {'selfPurchaseUser':filterUserId },
//             {'communityCommissionUser': filterUserId },
//             {'inviterCommissionUser': filterUserId }
//         ],
//         'balanceStatus' : balanceStatus};
//
//         var columnOption = {
//             'shareCommission': 1, 'selfPurchase': 1,
//             'communityCommission': 1,'inviterCommission': 1
//         };
//     mtOrder.find(findOption, columnOption).exec(function (error, result){
//         callback(null, exports.getSumCommission(result));
//     });
// };
//
// exports.getSumCommission  = function(result, callback)  {
//     var sum = 0;
//     if(result && result.length > 0) {
//         logger.debug("result.length..." + result.length);
//         async.eachSeries(result, function (row, callbackInner) {
//             var shareCommission = row.shareCommission;
//             var selfPurchase = row.selfPurchase;
//             var communityCommission = row.communityCommission;
//             var inviterCommission = row.inviterCommission;
//             logger.debug(shareCommission);
//             logger.debug(selfPurchase);
//             logger.debug(communityCommission);
//             logger.debug(inviterCommission);
//             if(shareCommission) {
//                 sum += shareCommission;
//                 logger.debug("shareCommission");
//             }
//             if(selfPurchase) {
//                 sum += selfPurchase;
//                 logger.debug("selfPurchase");
//             }
//             if(communityCommission) {
//                 sum += communityCommission;
//                 logger.debug("communityCommission");
//             }
//             if(inviterCommission) {
//                 sum += inviterCommission;
//                 logger.debug("inviterCommission");
//             }
//             callbackInner(false);
//         }, function (err) {
//             logger.debug("getSumCommission..." + sum);
//             return sum;
//         });
//     }
// };
//
// exports.getShareCommission = function(userId, balanceStatus, callback)  {
//     var filterUserId = mongoose.Types.ObjectId(userId);
//     var findOption = {
//         'shareCommissionUser': filterUserId,
//         'balanceStatus': balanceStatus
//     };
//     var columnOption = {
//         'shareCommission': 1
//     };
//     mtOrder.find(findOption, columnOption).exec(function (error, result){
//         var temp = exports.getSumCommission(result);
//         callback(null, temp);
//     });
// };
//
// exports.getSelfPurchase = function(userId, balanceStatus, callback)  {
//     var filterUserId = mongoose.Types.ObjectId(userId);
//     var findOption = {
//         'selfPurchaseUser': filterUserId,
//         'balanceStatus': balanceStatus
//     };
//     var columnOption = {
//         'selfPurchase': 1
//     };
//     mtOrder.find(findOption, columnOption).exec(function (error, result){
//         var temp = exports.getSumCommission(result);
//         callback(null, temp);
//     });
// };
//
// exports.getCommunityCommission = function(userId, balanceStatus, callback)  {
//     var filterUserId = mongoose.Types.ObjectId(userId);
//     var findOption = {
//         'communityCommissionUser': filterUserId,
//         'balanceStatus': balanceStatus
//     };
//     var columnOption = {
//         'communityCommission': 1
//     };
//     mtOrder.find(findOption, columnOption).exec(function (error, result){
//         var temp = exports.getSumCommission(result);
//         callback(null, temp);
//     });
// };
//
// exports.getInviterCommission = function(userId, balanceStatus, callback)  {
//     var filterUserId = mongoose.Types.ObjectId(userId);
//     var findOption = {
//         'inviterCommissionUser': filterUserId,
//         'balanceStatus': balanceStatus
//     };
//     var columnOption = {
//         'inviterCommission': 1
//     };
//     mtOrder.find(findOption, columnOption).exec(function (error, result){
//         var temp = exports.getSumCommission(result);
//         callback(null, temp);
//     });
// };